'''
Created on 2012-06-12

@author: alexandre
'''
import numpy as np
from os import path
import cPickle
import zlib

def ranking( valL, epsilon = 1e-8 ):
    """
    It returns the rank of each value in valL.
    For groupes having the same value (within epsilon), the rank is averaged
    TODO : for now, to be able to average rank of identical values, the algo is n^2 complexity. 
    It could be coded with a n log n complexity
    """
    
    rankL_= np.zeros( len(valL))
    rankL_[np.argsort(valL)] = np.arange(1,len(valL)+1)
    
    # now, we handle the fact that some val might have the same rank
    absDiffMat = np.abs(np.array([[ vi-vj for vi in valL] for vj in valL]))
    rankL =  [ np.mean( rankL_[row < epsilon] ) for row in absDiffMat ]
    
    # convert to int values that are not fractional (this is for printing reasons)
    for i,rank in enumerate(rankL):
        if np.abs(int(rank)-rank)< epsilon:
            rankL[i] = int(rank)
 
    
    assert np.abs(sum(rankL) - sum(rankL_)) < epsilon
    
    return rankL


def readFile( *args ):
    """
    A wrapper to simplify file reading
    fileName = path.join(*args)
    If fileName doesn't exist None is returned.
    """
    filePath = path.join( *args )
    if not path.exists( filePath ):
        return None
    with open( filePath, 'r' ) as fd:
        return fd.read() 
    
def writeFile( _str, *args ):
    """
    A wrapper to simplify file writing
    fileName = path.join(*args)
    """
    filePath = path.join( *args )
    with open( filePath, 'w' ) as fd:
        fd.write(_str) 
        
def writePklz( obj, *args ):
    writeFile( zlib.compress( cPickle.dumps(obj,cPickle.HIGHEST_PROTOCOL) ), *args )

def readPklz( *args ):
    with open( path.join(*args), 'r' ) as fd:
        data = fd.read() 
    return cPickle.loads(zlib.decompress( data ))